// import { useNavigate } from "react-router-dom";
import { history } from 'umi';
import * as api from '@/api/users';
import React, { Fragment, useState } from 'react';
import { Button, Checkbox, Form, Input, Spin, message } from 'antd';
import useStorage from '@/hooks/useStorage';
// import {connect} from "react-redux"
import './index.css';
// import useActionCreateor from "@/store/actions/userAction";

// 将dispatch方法映射到组件内
// const mapDispatchToProps = (dispatch:any) => {
//   return {
//     SetUserInfo(payload:any){
//       dispatch(useActionCreateor('SET_USERINFO',payload))
//     }
//   }
// }

const Login = () => {
  // 在本地存储token
  let [token, methods] = useStorage('qf-token');
  // 在本地存储userInfo
  let [userInfo, method] = useStorage('qf-userInfo');
  // 加载动画
  let [loading, setLoading] = useState<boolean>(false);
  // let navigate = useNavigate()

  // 表单验证通过
  const onFinish = async (values: any) => {
    console.log('Success:', values);
    // 打开加载动画
    setLoading(true);
    try {
      // 发起登录请求
      let res = await api.loginApi(values.username, values.password);
      console.log('login', res);
      // console.log(token)
      // 关闭加载动画
      setLoading(false);
      // 如果登陆成功
      if (res.data.state) {
        // 跳转到主页面
        history.push('/');
        // 将userInfo存储到redux
        // props.SetUserInfo!(res.data.userInfo)
        // 在本地存储一下token和userInfo
        methods.set(res.data.token);
        method.set(res.data.userInfo);
        // 成功提示框
        message.open({
          type: 'success',
          content: res.data.msg,
        });
      }
    } catch (e) {
      console.log(e);
      // 失败提示框
      message.open({
        type: 'error',
        content: '登陆失败',
      });
    }
  };

  // 表单验证不通过
  const onFinishFailed = (errorInfo: any) => {
    console.log('Failed:', errorInfo);
  };

  // 用户名校验
  const validatUsername = (rules: any, value: string) => {
    // 如果通过 返回Promise.resolve  如果不通过 返回Promise.reject
    if (!value) {
      return Promise.reject('输入不能为空');
    }
    if (value.length < 3) {
      return Promise.reject('用户名的长度不能小于3位');
    } else {
      return Promise.resolve('');
    }
  };

  // 密码校验
  const validatPassword = (rules: any, value: string) => {
    let reg = /^[\-_\w\d]{3,10}$/;
    if (!value) {
      return Promise.reject('密码不能为空');
    }
    if (reg.test(value)) {
      return Promise.resolve();
    } else {
      return Promise.reject('密码为3-10位');
    }
  };

  return (
    <Spin tip="正在登入..." spinning={loading} className="login-spin">
      <Fragment>
        {/* <div className="video">
                <video src={require("./video/预览视频1.mp4")} muted={true} loop={true} autoPlay={true} controls className="action"></video>
            </div>
             */}
        <div className="loginForm">
          <div className="systemName">
            <span>erp系统</span>
          </div>
          <Form
            name="loginForm"
            labelCol={{ span: 8 }}
            wrapperCol={{ span: 16 }}
            initialValues={{ remember: true }}
            onFinish={onFinish}
            onFinishFailed={onFinishFailed}
            autoComplete="off"
          >
            <Form.Item
              label="用户名"
              name="username"
              rules={[{ required: true, validator: validatUsername }]}
            >
              <Input />
            </Form.Item>

            <Form.Item
              label="密码"
              name="password"
              rules={[{ required: true, validator: validatPassword }]}
            >
              <Input.Password />
            </Form.Item>

            <Form.Item
              name="remember"
              valuePropName="checked"
              wrapperCol={{ offset: 8, span: 16 }}
            >
              <Checkbox>七天免登录</Checkbox>
            </Form.Item>

            <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
              <Button type="primary" htmlType="submit">
                登录
              </Button>
            </Form.Item>
          </Form>
        </div>
      </Fragment>
    </Spin>
  );
};

export default Login;
